﻿using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Threading.Tasks;
using SDCloudSolution.SDCloud.DataLayer.Model.Interfaces;
using SDCloudSolution.SDCloud.Entities.Models;

namespace SDCloudSolution.SDCloud.DataLayer.Model
{
    public class ModelStatisticsDataProvider : IModelStatisticsDataProvider
    {
        private readonly ModelDbContext _modelDbContext;

        public ModelStatisticsDataProvider(ModelDbContext modelDbContext)
        {
            _modelDbContext = modelDbContext;
        }

        protected IQueryable<ModelStatisticsEntity> ModelStatistics
        {
            get { return _modelDbContext.ModelStatistics.AsNoTracking(); }
        }

        /// <summary>
        /// Gets the model statistics by specific model identifier.
        /// </summary>
        /// <param name="modelId">The model identifier.</param>
        public Task<ModelStatisticsEntity> GetByModelIdAsync(int modelId)
        {
            return ModelStatistics.FirstOrDefaultAsync(modelStat => modelStat.ModelId == modelId);
        }

        /// <summary>
        /// Gets the model statistics by specific model identifiers.
        /// </summary>
        /// <param name="modelIds">The model ids.</param>
        public async Task<IEnumerable<ModelStatisticsEntity>> GetByModelIdsAsync(IEnumerable<int> modelIds)
        {
            return await ModelStatistics.Where(modelStat => modelIds.Contains(modelStat.ModelId)).ToListAsync();
        }

        /// <summary>
        /// Insert a new instance of model statistics information to storage.
        /// </summary>
        /// <param name="entity">The entity.</param>
        public Task InsertAsync(ModelStatisticsEntity entity)
        {
            _modelDbContext.ModelStatistics.Add(entity);
            return _modelDbContext.SaveChangesAsync();
        }

        /// <summary>
        /// Updates an exists instance of model statistics in storage.
        /// </summary>
        /// <param name="entity">The entity.</param>
        public Task UpdateAsync(ModelStatisticsEntity entity)
        {
            _modelDbContext.ModelStatistics.AddOrUpdate(entity);
            return _modelDbContext.SaveChangesAsync();
        }
    }
}
